//
//  HWGameLiveImManager.swift
//  PlayWithProject
//
//  Created by 王昌健 on 2021/10/28.
//

import UIKit
protocol HWLiveIMDelegate:AnyObject {
    /// 用户加入房间
    func userEnterRoom(userModel:HWGameLiveChatModel)
    /// 用户离开直播间
    func userLeaveRoom(userModel:HWGameLiveChatModel)
    /// 收到群消息
    /// - Parameter userModel: 用户信息
    func receiveGroupText(userModel:HWGameLiveChatModel)
    ///收到群自定义消息
    func receiveGroupCustomMessage(typeDic:NSDictionary)
}
class HWGameLiveImManager: NSObject {
    var imManager :V2TIMManager {
        return V2TIMManager.sharedInstance()
    }
    //房间ID
    var roomId:String = ""
    weak var delegate : HWLiveIMDelegate?
    public static let shared = HWGameLiveImManager()
    
}
extension HWGameLiveImManager {
    /// 进入房间
    func enterRoom(roomId:String,failure:@escaping(_:NSInteger,_:String)->()) -> Void {
        self.roomId = roomId
        self.imManager.joinGroup(roomId, msg: "") {
//            self.imManager.removeGroupListener(listener: self)
            self.imManager.setGroupListener(nil)
            self.imManager.removeSignalingListener(listener: self)
            self.imManager.removeSimpleMsgListener(listener: self)
            
//            self.imManager.addGroupListener(listener: self)
            self.imManager.setGroupListener(self)
            self.imManager.addSignalingListener(listener: self)
            self.imManager.addSimpleMsgListener(listener: self)
//            self.imManager.getGroupMemberList(self.roomId, filter: .GROUP_MEMBER_FILTER_ALL, nextSeq: 0) { nextSeq, list in
//                print(list)
//            } fail: { code, message in
//
//            }

            self.enterRoomSuccessGetGroupInfo(roomId: self.roomId) { code, message in
                
            }
        } fail: { code, message in
            failure(NSInteger(code),message ?? "")
        }
    }
    
    //进入房间获取信息
    func enterRoomSuccessGetGroupInfo(roomId:String,failure:@escaping(_:NSInteger,_:String)->()) -> Void {
        self.imManager.getGroupAttributes(roomId, keys: nil) { attributes in
            print(attributes ?? "attributes未获取到")

        } fail: { code, message in
            print("进入房间获取信息出错")
        }

    }
    
    //发送文字消息
    func sendRoomTextMessage(text:String,callBack:@escaping(_:NSInteger,_:String)->()) -> Void {
        imManager.sendGroupTextMessage(text, to: self.roomId, priority: V2TIMMessagePriority.PRIORITY_NORMAL) {
            callBack(0,"发送成功")
        } fail: { code, message in
            callBack(NSInteger(code),message ?? "")
        }
    }
//
//    func receiveMessage(callBack:@escaping(_:NSInteger,_:String)->()) -> Void {
//
//    }
    
    func exitRoom(callBack:@escaping(_:NSInteger,_:String)->()) -> Void {
        imManager.quitGroup(roomId) {
            callBack(0,"退出成功")
            
        } fail: { code, message in
            callBack(NSInteger(code),message ?? "")
        }
    }
    
}
extension HWGameLiveImManager:V2TIMGroupListener,V2TIMSignalingListener,V2TIMSimpleMsgListener {
    /// 新成员进入房间
    func onMemberEnter(_ groupID: String!, memberList: [V2TIMGroupMemberInfo]!) {
        if groupID != self.roomId {
            return
        }
        
        for (_,obj) in memberList.enumerated() {
            let userInfo = HWGameLiveChatModel()
            userInfo.userName = obj.nickName
            userInfo.userId = obj.userID
            userInfo.userFace = obj.faceURL
            userInfo.msgType = HWLiveRoomMsgType.userEnterRoom
            if userInfo.userId == HWLocallyStoredData.getLoginUserID() {
                userInfo.userType = .owner
            }
            self.delegate?.userEnterRoom(userModel: userInfo)
        }
    }
    
    //用户离开
    func onMemberLeave(_ groupID: String!, member: V2TIMGroupMemberInfo!) {
        if groupID != self.roomId {
            return
        }
        let userInfo = HWGameLiveChatModel()
        userInfo.userName = member.nickName
        userInfo.userId = member.userID
        userInfo.userFace = member.faceURL
        userInfo.msgType = HWLiveRoomMsgType.userLeaveRoom
        self.delegate?.userLeaveRoom(userModel: userInfo)
    }
    
    //收到群消息
    func onRecvGroupTextMessage(_ msgID: String!, groupID: String!, sender info: V2TIMGroupMemberInfo!, text: String!) {
        let userModel = HWGameLiveChatModel()
        userModel.userName = info.nickName
        userModel.userFace = info.faceURL
        userModel.userId = info.userID
        userModel.msgType = .receive
        userModel.text = text
        self.delegate?.receiveGroupText(userModel: userModel)
    }
    
    //收到自定义群消息
    func onRecvGroupCustomMessage(_ msgID: String!, groupID: String!, sender info: V2TIMGroupMemberInfo!, customData data: Data!) {
        //        let json = String(data: data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
        let dic = HWUniversal.DataToJSONObject(data: data) as! NSDictionary
        self.delegate?.receiveGroupCustomMessage(typeDic: dic)
        
    }
}

